// GpsActivity.java
package com.example.app3_1;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;

public class GpsActivity extends AppCompatActivity {
    private static final String TAG = "GpsActivity";
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;

    private GpsBindService gpsService;
    private boolean isBound = false;
    private TextView locationTv;
    private TextView statusTv;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "Service连接成功");
            GpsBindService.GpsBinder binder = (GpsBindService.GpsBinder) service;
            gpsService = binder.getService();
            isBound = true;

            // 注册回调，实时更新UI
            gpsService.setCallback((lat, lon) -> runOnUiThread(() -> {
                String location = String.format("当前位置：纬度 %.4f°，经度 %.4f°", lat, lon);
                locationTv.setText(location);
                statusTv.setText("GPS状态：位置已更新");
                Log.d(TAG, "位置更新: " + location);
            }));

            statusTv.setText("GPS状态：服务已连接，等待位置更新");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "Service连接断开");
            isBound = false;
            statusTv.setText("GPS状态：服务连接断开");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);
        Log.d(TAG, "GpsActivity创建");

        // 初始化视图
        locationTv = findViewById(R.id.location_tv);
        statusTv = findViewById(R.id.status_tv);

        // 设置初始显示
        locationTv.setText("当前位置：等待GPS定位...");
        statusTv.setText("GPS状态：初始化中");

        // 检查权限
        if (checkLocationPermission()) {
            startGpsService();
        } else {
            requestLocationPermission();
        }
    }

    // 检查位置权限
    private boolean checkLocationPermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED;
    }

    // 请求位置权限
    private void requestLocationPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                },
                LOCATION_PERMISSION_REQUEST_CODE);
    }

    // 启动GPS服务
    private void startGpsService() {
        Log.d(TAG, "启动GPS服务");
        try {
            Intent intent = new Intent(this, GpsBindService.class);
            bindService(intent, connection, BIND_AUTO_CREATE);
            statusTv.setText("GPS状态：正在连接服务...");
        } catch (Exception e) {
            Log.e(TAG, "启动GPS服务失败", e);
            statusTv.setText("GPS状态：服务启动失败");
            Toast.makeText(this, "GPS服务启动失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限授予，启动服务
                startGpsService();
            } else {
                // 权限拒绝
                statusTv.setText("GPS状态：位置权限被拒绝");
                Toast.makeText(this, "需要位置权限才能使用GPS功能", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "GpsActivity销毁");
        if (isBound) {
            unbindService(connection);
            isBound = false;
            Log.d(TAG, "Service已解绑");
        }
    }
}